"""
project: apiAutoTestWeb
file: __init__.py
author: zy7y
date: 2021/4/17
"""
from fastapi import FastAPI, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from tortoise.contrib.fastapi import register_tortoise

import core
from .auth import auth
from .user import users

# 挂载数据库orm 日志
from db.log import logger_tortoise

def create_app():
    app = FastAPI(title="apiAutoTestWebApi")

    # 挂载静态文件
    app.mount("/static", StaticFiles(directory="static"), name="static")

    # 挂载 数据库
    register_tortoise(
        app,
        db_url="sqlite://db.sqlite3",
        modules={"models": ["db.models"]},
        # 生成表
        generate_schemas=True,
        # 使用异常，当无数据是自动返回
        add_exception_handlers=True,
    )

    # 跨域中间件
    app.add_middleware(
        CORSMiddleware,
        allow_origins=core.setting.ORIGINS,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # 挂载子路由
    app.include_router(auth)
    app.include_router(users, dependencies=[Depends(core.get_current_user)])

    return app
